<template>
  <div>
    <a-upload
      name="file"
      accept="image/*"
      list-type="picture-card"
      :show-upload-list="false"
      :customRequest="uploadImageFile"
      :beforeUpload="beforeUpload"
    >
      <div>
        <a-icon :type="uploadStatus ? 'loading' : 'plus'" />
        <div class="ant-upload-text">
          上传图片
        </div>
      </div>
    </a-upload>
    <div style="margin-top: -21px;">最多{{ maxNum }}张图片</div>
    <viewer class="image-list" v-if="images.length > 0">
      <div v-for="(item, index) in images" :key="index" class="img-item">
        <img :src="item" />
        <a-icon type="close" @click="removeImages(index)" style="cursor: pointer;" />
      </div>
    </viewer>
  </div>
</template>

<script>
import Vue from 'vue'
import Viewer from 'v-viewer'
import 'viewerjs/dist/viewer.css'

Vue.use(Viewer, {
  defaultOptions: {
    zIndex: 100,
    inline: false,
    button: true,
    navbar: false,
    title: false,
    toolbar: true,
    tooltip: true,
    movable: true,
    zoomable: true,
    rotatable: false,
    scalable: false,
    transition: true,
    fullscreen: true,
    keyboard: false,
    loop: true
  }
})

export default {
  name: 'MultiImages',
  props: {
    urls: {
      type: Array,
      default: () => []
    },
    // 最大数量
    maxNum: {
      type: Number,
      default: 9
    }
  },
  data () {
    return {
      images: [],
      uploadStatus: false
    }
  },
  mounted() {
    this.images = this.urls || []
  },
  methods: {
    beforeUpload (file) {
      if (this.images.length >= this.maxNum) {
        this.$message.error(`最多上传${ this.maxNum }张图片`)
        return false
      }
    },
    // 上传图片
    uploadImageFile (file) {
      console.log('file', file)
      this.uploadStatus = true // 按钮状态
      const formData = new FormData()
      formData.append('file', file.file)
      this.$common.uploadImageFile(formData).then(data => {
        console.log(data)
        if (data.code === 200) {
          const result = data.result
          this.images.push(result.url)
          this.$emit('ok', this.images)
        } else {
          this.$message.error(data.message)
        }
      }).finally(() => {
        this.uploadStatus = false
      })
    },
    removeImages (index) {
      if (this.images[index] !== undefined) this.images.splice(index, 1)
    }
  },
  watch: {
    urls (val) {
      this.images = val || []
    }
  }
}
</script>

<style lang="less" scoped>
.image-list {
  display: flex;
  flex-wrap: wrap;
  .img-item {
    width: 100px;
    height: 100px;
    margin-right: 10px;
    margin-bottom: 10px;
    display: flex;
    cursor: pointer;
    position: relative;
    img {
      width: 100%;
      height: 100%;
    }
    i{
      position: absolute;
      right: 5px;
      top: 5px;
    }
  }
}
</style>
